package com.taotao.patient.service.impl;

import com.taotao.common.security.utils.SecurityUtils;
import com.taotao.patient.domain.request.GroupRequest;
import com.taotao.patient.domain.request.MessageRequest;
import com.taotao.patient.domain.response.GroupResponse;
import com.taotao.patient.domain.response.MessageResponse;
import com.taotao.patient.mapper.PatientMapper;
import com.taotao.patient.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @className: PatientServiceImpl
 * @author: ZhangYuQi
 * @date: 2025/2/24 下午7:53
 * @Version: 1.0
 * @description:
 */

@Service
public class PatientServiceImpl implements PatientService {

    @Autowired
    private PatientMapper patientMapper;


    @Override
    public List<GroupResponse> selectGroupsAndPatients() {

        //获取当前登录人信息
        Long userId = SecurityUtils.getUserId();
        return patientMapper.selectGroupsAndPatients(userId);
    }

    @Override
    public void insertGroup(String groupName) {
        //获取当前登录人信息
        Long userId = SecurityUtils.getUserId();
        patientMapper.insertGroup(groupName,userId);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteGroup(Long groupId) {
        //删除分组
        patientMapper.deleteGroup(groupId);
        //删除分组下所有的患者
        patientMapper.deletePatientByGroupId(groupId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertMessage(MessageRequest request) {
        //获取当前登录人
        Long userId = SecurityUtils.getUserId();
        request.setDoctorId(userId);
        patientMapper.insertMessage(request.getMessageContent(),request.getDoctorId());
        //记录历史消息记录
        patientMapper.insertMessageHistory(request.getId(),request.getUserIds());
    }

    @Override
    public List<MessageResponse> selectMessageHistory() {
        //获取当前登录人Id
        Long userId = SecurityUtils.getUserId();
        return patientMapper.selectMessageHistory(userId);
    }

    @Override
    public void insertGroupUser(GroupRequest request) {
        //获取当前登录人id
        Long userId = SecurityUtils.getUserId();
        //先清空除默认分组其他分组的患者信息
        patientMapper.deleteGroupUser(userId,request.getPatientId());
        //循环添加新的患者分组信息
        patientMapper.insertGroupUser(request.getPatientId(),request.getGroupIds());
    }
}
